package org.skycloud.mybatis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.skycloud.mybatis.utils.DatabaseIdUtils;

final class DatabaseIdProviderImpl implements DatabaseIdProvider {

	private Map<Pattern, String> vendorMapping;

	DatabaseIdProviderImpl(Map<String, String> vendorMapping) {
		if (vendorMapping != null && !vendorMapping.isEmpty()) {
			this.vendorMapping = new HashMap<Pattern, String>();
			for (Entry<String, String> entry : vendorMapping.entrySet()) {
				this.vendorMapping.put(Pattern.compile(entry.getKey()), entry.getValue());
			}
		}
	}

	@Override
	public void setProperties(Properties properties) {
	}

	@Override
	public String getDatabaseId(DataSource dataSource) throws SQLException {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			String databaseProductName = conn.getMetaData().getDatabaseProductName();

			if (vendorMapping != null) {
				for (Entry<Pattern, String> entry : vendorMapping.entrySet()) {
					if (entry.getKey().matcher(databaseProductName).matches()) {
						return entry.getValue();
					}
				}
			}

			return DatabaseIdUtils.getDatabaseId(databaseProductName);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException ignore) {
				}
			}
		}
	}
}